import MediaMenuTree from "@/views/media/components/MediaMenuTree";
import List from "@/components/List";
import Pagination from '@/components/Pagination'

import MediaApi from '@/api/media'

import {fileTypeMap, webImageUrl, fileTypeOpts, FILETYPE} from '@/views/media/media-center/const'

const TYPE_MEDIA_CENTER = 1
const TYPE_MEDIA_TEMPLATE = 2
const TYPE_MEDIA_MKSHOW = 3
const TYPE_MEDIA_PUBSHOW = 4
const TYPE_MEDIA_AUDIT= 5
const meidaApiMap = {
  [TYPE_MEDIA_CENTER]: {
    get: MediaApi.get,
    del: MediaApi.del,
    add: function(form) {
      switch (form.type) {
        case FILETYPE.FOLDER:
          return MediaApi.saveFolder
        case FILETYPE.QRCODE:
          return MediaApi.saveQRCode
        case FILETYPE.DVB:
          if (form.dvbType == '2') {
            return MediaApi.saveDvb
          } else {
            return MediaApi.save
          }
        case FILETYPE.LOCAL_TEXT:
          return MediaApi.saveText
        default:
          return MediaApi.save
      }
    },
    update: function(form) {
      return String(form.type) === FILETYPE.FOLDER
        ? MediaApi.modifyFolder : MediaApi.modify
    }
  },
  [TYPE_MEDIA_MKSHOW]: {
    get: MediaApi.getProgram,
    del: MediaApi.delProgram,
    add: MediaApi.saveProgram,
    update: MediaApi.updateProgram
  },
  [TYPE_MEDIA_AUDIT] :{
    get: MediaApi.getAuditPage,
    del: MediaApi.del,
    audit: MediaApi.mediaAudit
  }
}

// 当操作做完后需要处理的事情
function afterAciton(media_type) {
  switch (media_type) {
    case TYPE_MEDIA_MKSHOW:
      this.setNeedFetching({change: ['media', 'template']})
      break;
    default:
      break;
  }
}

function getCommonMixn() {
  return {
    components: {
      MediaMenuTree,
      List,
      Pagination,
    },
    data() {
      return {
        mediaData: [],
        page: {
          current: 1,
          size: 15,
          total: 0
        },
        folderId: 0,
        listFetching: false,
        isOtherMenu: false
      }
    },
    created() {

    },
    methods: {
      pageChange({page: current, limit: size}) { // 分页改变
        this.page = {
          ...this.page,
          current: size != this.page.size ? 1 : current,
          size
        } 
        this.fetchList()
      },
      currentNodeDataChange(data) { // 左侧目录树被点击
        this.isOtherMenu = !!data._isOther
        if (data.id === -1 || data.id === -2) {
          this.folderId = data.id
          this.page.current = 1
          this.page.total = 0
          this.mediaData = []
          return 
        } else if (data._isSub || data._isOther) { // 下级用户目录被点击
          this.folderId = data && data.id != undefined ? data.id : 0
          if (data.ownerUserId) {
            this.$set(this.search, 'ownerUserId', data.ownerUserId)
          } else {
            this.$delete(this.search, 'ownerUserId')
          }
        } else {
          this.folderId = data ? data.id : 0
          this.$delete(this.search, 'ownerUserId')
        }
        this.page.current = 1
        this.fetchList()
      }
    }
  }
}

// 请求列表方法
function mediaList(media_type) {
  return async function fetchList() {
    if (this.listFetching) return 
    this.listFetching = true
    try {
      const {current, size} = this.page // 分页参数
      const folderId = this.folderId // 目录id
      let params = {
        current,
        size,
        ...this.search
      }
      
      /** 对不同页面的请求作不同处理 */
      const getApi = meidaApiMap[media_type].get
      // 媒体审核
      if (media_type === TYPE_MEDIA_AUDIT) {
        if (this.activeName2 === 'first') {
          params.auditState = 0
        } else if(this.activeName2 === 'second') {
          params.auditState = 1
        } else {
          params.auditState = -1
        }
        if (this.activeName === 'first') {
          params.folderId = this.folderId
        } else {
          params.queryTagId = this.tagIds
          delete params.ownerUserId
        }
        if(params.folderId === -3) {
          delete params.folderId
        }
        if (this.sort.sortField) {
          params.orderType = this.sort.sortField
          params.ordersParam = this.sort.orders
        } else {
          params.orderType = 12 // 默认为创建时间倒序排序
          params.ordersParam = 'desc'
        }
      }
      
      // 媒体中心
      if (media_type === TYPE_MEDIA_CENTER) {
        if (this.activeName === 'first') {
          params.folderId = this.folderId
        } else {
          params.queryTagId = this.tagIds
          delete params.ownerUserId
        }
        if (this.sort.sortField) {
          params.orderType = this.sort.sortField
          params.ordersParam = this.sort.orders
        } else {
          params.orderType = 10 // 默认为创建时间倒序排序
          params.ordersParam = 'desc'
        }
      }

      // 节目制作
      if (media_type === TYPE_MEDIA_MKSHOW) {
        params.auditState = this.filterAuditState
        if (this.activeName === 'first') {
          params.folderId = this.folderId
        } else {
          params.tagId = this.tagIds
          delete params.ownerUserId
        }
        if (this.sort.orderType) {
          params.orderType = this.sort.orderType
          params.ordersParam = this.sort.ordersParam
        }
      }

      
      
      const res = await getApi(params)
      this.mediaData = res.records.map(item => {
        // 不同的页面对列表数据的处理方式

        // 媒体中心
        if (media_type === TYPE_MEDIA_CENTER) {
          // let argus = JSON.parse(item.argus)
          // let attributes = argus.attributes
          // if (attributes && typeof attributes === 'string') {
          //   attributes = JSON.parse(attributes)
          // }
          // console.log(attributes)
          item.showType = 'media'
          return {
            // ...argus,
            ...item,
            // innerTags: item.innerTagss,
            // tagId: item.tagIds,
            // attributes: attributes ? attributes : {}
          }
        }

        // 节目制作
        if (media_type === TYPE_MEDIA_MKSHOW) {
          item.showType = 'program'
          return {
            ...item
          }
        }
        
        // 媒体审核
        if(media_type === TYPE_MEDIA_AUDIT) {
          item.showType = 'mediaAudit'
          return {
            ...item
          }
        }
      })
      this.page.current =  Number(res.current)
      this.page.total = Number(res.total)
    } catch (error) {
      console.log(error)
    } finally {
      this.listFetching = false
    }
  }
}

// 审核
function mediaAudit(media_type) {
  return async function audit(auditState, reason, file) {
    if(media_type === TYPE_MEDIA_AUDIT) {
      let _fileIds
      if (file instanceof Array) {
        _fileIds = file.map(f => f.id)
      } else {
        _fileIds = [file.id]
      }
      let _form = {}
      _form.ids = _fileIds
      _form.auditState = auditState
      _form.auditReason = reason
      console.log(media_type, _form, auditState, reason)
      const api = meidaApiMap[media_type].audit
      const res = await api(_form)
      this.$message.success('审核成功')
      this.fetchList()
    }
  }
}

// 列表删除
function listDel(media_type) {
  return async function delMedia(file, queryData) {
    let _fileIds
    if (file instanceof Array) {
      _fileIds = file.map(f => f.id)
    } else {
      _fileIds = file ? [file.id] : []
    }

    let _form = {}
    if (this.search.ownerUserId) _form.ownerUserId = this.search.ownerUserId
    // 不同页面间的处理
    const delApi = meidaApiMap[media_type].del
    // 媒体中心
    if (media_type === TYPE_MEDIA_CENTER || media_type === TYPE_MEDIA_AUDIT) {
      _form.id = _fileIds
    }
    // 节目制作
    if (media_type === TYPE_MEDIA_MKSHOW) {
      _form.programId = _fileIds
    }

    try {
      const res = await delApi({
        ..._form,
        ...queryData
      })
      this.allSize = false
      this.$message.success('删除成功')
      // if(_fileIds.length == this.mediaData.length) {
      //   this.page.current = this.page.current == 0 ? 0 : this.page.current-1
      // }
      this.page.current = 1
      afterAciton.call(this, media_type)
      this.fetchList()
    } catch (error) {
      console.warn('delMedia---', error)
    }
  }
}

// 列表新增
function listAdd(media_type) {
  return async function addClickHandle(form, cb) {
    let _form = {
      ...form
    }
    if (this.search.ownerUserId) _form.ownerUserId = this.search.ownerUserId
    // 不同页面间的处理
    let addApi = meidaApiMap[media_type].add
    // 媒体中心
    if (media_type === TYPE_MEDIA_CENTER) {
      addApi = addApi(_form)
    }

    try {
      const res = await addApi(_form)
      cb && cb()
      this.$message.success('添加成功')
      afterAciton.call(this, media_type)
      this.fetchList()
      if (media_type === TYPE_MEDIA_CENTER) {
        if (this.webCatchFormDialog.show) {
          this.webCatchFormDialog.show = false
        }
      }
    } catch (error) {
      cb && cb(true)
      console.warn('addClickHandle---', error)
    }
  }
}

// 列表修改
function listUpdate(media_type) {
  return async function updateClickHandle(form, cb) {
    console.log('updateForm', form)
    try {
      const _form = {
        ...form
      }
      if (this.search.ownerUserId) _form.ownerUserId = this.search.ownerUserId
      // 不同页面间的处理
      let updateApi = meidaApiMap[media_type].update
      // 媒体中心
      if (media_type === TYPE_MEDIA_CENTER) {
        let nameArr = _form.name.split('.')
        _form.suffix = `.${nameArr.pop()}`
        _form.name = nameArr.join('.')
        // 级联更新
        let cascadeUpdate = false
        const id = _form.id
        if(_form.refCount > 0 && id > 0) {
          const res = await this.$confirm('提示', '素材已被使用,是否需要级联更新?')
          if(res) {
            cascadeUpdate = true
          }
        }
        _form.cascadeUpdate = cascadeUpdate
        updateApi = updateApi(_form)
        delete _form.thumbnailFile
      }
      // 节目制作
      if (media_type === TYPE_MEDIA_MKSHOW) {
        delete _form.auditState
      }
      
      const res = await updateApi(_form)
      this.$message.success('修改成功')
      cb && cb()
      afterAciton.call(this, media_type)
      this.fetchList()
    } catch (error) {
      cb && cb(true)
      console.warn('addClickHandle---', error)
    }
  }
}

// type 1 - 媒体中心 2 - 模板 3 - 节目制作 4 - 节目发布
function genMediaMixin(type) {
  const base = getCommonMixn()
  // 加入CURD方法
  base.methods.fetchList = mediaList(type)
  base.methods.delMedia = listDel(type)
  base.methods.addClickHandle = listAdd(type)
  base.methods.updateClickHandle = listUpdate(type)
  switch (Number(type)) {
    case TYPE_MEDIA_CENTER:
      break;
    case TYPE_MEDIA_TEMPLATE:
      break;
    case TYPE_MEDIA_MKSHOW:
      // 节目制作另存
      base.methods.saveClickHandle = async function saveClickHandle(form, cb) {
        try {
          let _form = {
            ...form
          }
          delete _form.auditState
          if (this.search.ownerUserId) _form.ownerUserId = this.search.ownerUserId
          const res = await MediaApi.saveAsProgram(_form)
          cb && cb()
          this.$message.success('另存成功')
          afterAciton.call(this, TYPE_MEDIA_MKSHOW)
          this.fetchList()
        } catch (error) {
          console.log('error', error)
        }
      }
      break;
    case TYPE_MEDIA_PUBSHOW:
      break;
    case TYPE_MEDIA_AUDIT:
      base.methods.mediaAudit = mediaAudit(type)
      break;
    default:
      break;
  }
  return base
}


const MEDIA_MIXIN_CONST = {
  TYPE_MEDIA_CENTER,
  TYPE_MEDIA_TEMPLATE,
  TYPE_MEDIA_MKSHOW,
  TYPE_MEDIA_PUBSHOW,
  TYPE_MEDIA_AUDIT
}
export {
  genMediaMixin,
  MEDIA_MIXIN_CONST
}

